import sys
import traceback


# 返回错误信息
def getError():
    exc_type, exc_obj, exc_tb = sys.exc_info()
    print(f"异常类型: {exc_type.__name__}")
    print(f"错误信息: {exc_obj}")
    print(f"发生异常的文件: {exc_tb.tb_frame.f_code.co_filename}")
    print(f"发生异常的行号: {exc_tb.tb_lineno}")
    return {
        "type": exc_type.__name__,
        "msg": exc_obj,
        "file": exc_tb.tb_frame.f_code.co_filename,
        "line": exc_tb.tb_lineno
    }

# 返回错误信息，index从0开始计数，即第一行错误信息为0
def getError2(index):
    # 捕获异常并通过信号传递
    exc_type, exc_value, exc_traceback = sys.exc_info()  # 获取当前异常的相关信息
    tb = traceback.extract_tb(exc_traceback)  # 提取堆栈信息
    error_file = tb[index].filename  # 获取错误文件
    error_line = tb[index].lineno  # 获取错误行号
    return {
        "type": exc_type.__name__,
        "msg": exc_value,
        "file": error_file,
        "line": error_line,
        "code": traceback.format_exc()  # 错误的代码，所有的
    }